<template>
  <div class="session-list">
    <div class="session-list-header">
      <h3>会话列表</h3>
      <el-button
        type="primary"
        size="small"
        @click="handleCreateSession"
        :icon="Plus"
        circle
      />
    </div>
    
    <el-scrollbar class="session-list-content">
      <div v-if="sessions.length > 0">
        <el-tooltip
          v-for="session in sessions"
          :key="session.id"
          :content="session.title"
          placement="right"
        >
          <div
            :class="['session-item', { active: session.id === currentSessionId }]"
            @click="handleSelectSession(session.id)"
          >
            <div class="session-item-content">
              <div class="session-title">{{ session.title }}</div>
              <div class="session-meta">
                <span class="session-time">{{ formatTime(session.lastUpdated) }}</span>
              </div>
            </div>
            <el-popconfirm
              title="删除会话"
              description="确定要删除这个会话吗？删除后无法恢复。"
              confirm-button-text="删除"
              cancel-button-text="取消"
              @confirm="handleDeleteSession(session.id)"
              @click.stop
            >
              <template #reference>
                <el-button
                  text
                  type="danger"
                  size="small"
                  :icon="Delete"
                  circle
                  @click.stop
                />
              </template>
            </el-popconfirm>
          </div>
        </el-tooltip>
      </div>
      
      <div v-else class="empty-sessions">
        <el-empty description="暂无会话" :image-size="80" />
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import {
  getAllSessions,
  getCurrentSessionId,
  createNewSession,
  deleteSession
} from '../utils/storage'

const props = defineProps({
  currentSessionId: {
    type: String,
    default: null
  }
})

const emit = defineEmits(['session-change', 'session-create', 'session-delete'])

const sessions = ref([])

// 加载会话列表
const loadSessions = () => {
  sessions.value = getAllSessions()
  // 如果没有会话，创建一个
  if (sessions.value.length === 0) {
    const newSessionId = createNewSession()
    sessions.value = getAllSessions()
    // 只在初始化时触发事件
    if (!props.currentSessionId) {
      emit('session-create', newSessionId)
      emit('session-change', newSessionId)
    }
  }
}

// 选择会话
const handleSelectSession = (sessionId) => {
  if (sessionId !== props.currentSessionId) {
    emit('session-change', sessionId)
  }
}

// 创建新会话
const handleCreateSession = () => {
  const newSessionId = createNewSession()
  loadSessions()
  emit('session-create', newSessionId)
  emit('session-change', newSessionId)
}

// 删除会话
const handleDeleteSession = (sessionId) => {
  deleteSession(sessionId)
  loadSessions()
  emit('session-delete', sessionId)
  
  // 如果删除的是当前会话，通知父组件切换
  if (sessionId === props.currentSessionId) {
    const currentId = getCurrentSessionId()
    emit('session-change', currentId)
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else if (diff < 604800000) {
    return `${Math.floor(diff / 86400000)}天前`
  } else {
    return date.toLocaleString('zh-CN', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
}

// 监听会话列表变化
watch(() => props.currentSessionId, () => {
  loadSessions()
})

onMounted(() => {
  loadSessions()
})
</script>

<style scoped>
.session-list {
  width: 250px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color);
  border-right: 1px solid var(--el-border-color-light);
}

.session-list-header {
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--el-border-color-light);
  background: var(--el-bg-color);
}

.session-list-header h3 {
  margin: 0;
  font-size: 1rem;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.session-list-content {
  flex: 1;
  padding: 0.5rem;
}

.session-list-content :deep(.el-scrollbar__wrap) {
  padding: 0;
}

.session-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.75rem;
  margin-bottom: 0.5rem;
  background: var(--el-fill-color-blank);
  border-radius: var(--el-border-radius-base);
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid transparent;
}

.session-item:hover {
  background: var(--el-fill-color-light);
  border-color: var(--el-border-color);
}

.session-item.active {
  background: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary);
}

.session-item-content {
  flex: 1;
  min-width: 0;
}

.session-title {
  font-size: 0.875rem;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 0.25rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.session-meta {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.75rem;
  color: var(--el-text-color-secondary);
}

.session-time {
  flex: 1;
}

.session-count {
  color: #9ca3af;
}

.empty-sessions {
  padding: 2rem 1rem;
  text-align: center;
}

@media (max-width: 768px) {
  .session-list {
    width: 100%;
    height: auto;
    max-height: 200px;
    border-right: none;
    border-bottom: 1px solid var(--el-border-color-light);
  }
  
  .session-list-content {
    display: flex;
    overflow-x: auto;
    padding: 0.5rem;
    gap: 0.5rem;
  }
  
  .session-item {
    min-width: 200px;
    margin-bottom: 0;
  }
}
</style>

